<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>母鸡下蛋游戏</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f3f3f3;
    }
    canvas {
      display: block;
      margin: 0 auto;
      background-color: #cfe2f3;
    }
    #score {
      font-size: 20px;
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <h1>母鸡下蛋游戏</h1>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <div id="score">时间: <span id="timer">30</span> 秒</div>

  <script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');

    // 游戏常量
    const chickenRadius = 30;       // 母鸡半径
    const eggRadius = 15;           // 鸡蛋半径
    const maxEggSpeed = 5;          // 最快下蛋速度
    const minEggSpeed = 10;         // 最慢下蛋速度
    const gameDuration = 30;        // 游戏总时间，单位：秒

    let eggs = [];                  // 存储鸡蛋
    let eggSpeed = minEggSpeed;     // 初始下蛋速度
    let score = 0;                  // 计分
    let startTime = Date.now();     // 游戏开始时间
    let timerInterval;

    // 获取麦克风音量
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const analyser = audioContext.createAnalyser();
    let microphoneStream;

    // 启动麦克风并进行音量分析
    async function startMicrophone() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        microphoneStream = stream;
        const source = audioContext.createMediaStreamSource(stream);
        source.connect(analyser);
        analyser.fftSize = 256; // 设置FFT大小
      } catch (err) {
        alert('无法访问麦克风！');
      }
    }

    // 获取当前音量
    function getVolume() {
      const bufferLength = analyser.frequencyBinCount;
      const dataArray = new Uint8Array(bufferLength);
      analyser.getByteFrequencyData(dataArray);
      let sum = 0;
      for (let i = 0; i < bufferLength; i++) {
        sum += dataArray[i];
      }
      return sum / bufferLength; // 返回平均音量值
    }

    // 生成一个新的鸡蛋
    function generateEgg() {
      const egg = {
        x: canvas.width / 2,
        y: chickenY - chickenRadius,  // 在母鸡头上生成鸡蛋
        speed: eggSpeed,
      };
      eggs.push(egg);
    }

    // 更新鸡蛋的位置
    function updateEggs() {
      for (let i = 0; i < eggs.length; i++) {
        const egg = eggs[i];
        egg.y += egg.speed;
        if (egg.y > canvas.height) {
          eggs.splice(i, 1);
          i--;
          score++;
        }
      }
    }

    // 绘制母鸡和鸡蛋
    function drawGame() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制母鸡
      ctx.beginPath();
      ctx.arc(canvas.width / 2, chickenY, chickenRadius, 0, Math.PI * 2, false);
      ctx.fillStyle = 'red';
      ctx.fill();
      ctx.closePath();

      // 绘制鸡蛋
      for (const egg of eggs) {
        ctx.beginPath();
        ctx.arc(egg.x, egg.y, eggRadius, 0, Math.PI * 2, false);
        ctx.fillStyle = 'yellow';
        ctx.fill();
        ctx.closePath();
      }

      // 显示分数和剩余时间
      ctx.font = '20px Arial';
      ctx.fillStyle = 'black';
      ctx.fillText(`时间: ${Math.max(0, gameDuration - Math.floor((Date.now() - startTime) / 1000))} 秒`, 10, 30);
      ctx.fillText(`得分: ${score}`, 10, 60);
    }

    // 更新游戏状态
    function update() {
      const volume = getVolume();
      eggSpeed = Math.max(minEggSpeed, Math.min(maxEggSpeed, Math.floor(volume / 10))); // 根据音量调整下蛋速度
      if (Math.random() < 0.02) { // 通过概率控制生成鸡蛋
        generateEgg();
      }
      updateEggs();
      drawGame();
    }

    // 启动游戏
    function startGame() {
      startMicrophone();
      timerInterval = setInterval(() => {
        const timeLeft = Math.max(0, gameDuration - Math.floor((Date.now() - startTime) / 1000));
        if (timeLeft === 0) {
          clearInterval(timerInterval);
          alert('游戏结束！得分: ' + score);
        }
        document.getElementById('timer').innerText = timeLeft;
      }, 1000);

      function gameLoop() {
        update();
        requestAnimationFrame(gameLoop);
      }

      gameLoop();
    }

    // 初始化
    const chickenY = canvas.height - chickenRadius - 50; // 设置母鸡的位置
    startGame();

  </script>
</body>
</html>
